<?php
/**
 * 权限管理之角色管理
 * Date: 2015/6/17
 * Time: 13:44
 */

namespace AdminV3\Controller;
use Think\Controller;
class RoleController extends CommonController
{
    //显示roleIList
    public function index()
    {
        $list = M('role')->select();
        foreach($list as $k=>$v){
            $num = M('access')->where('role_id='.$v['id'])->field('count(node_id) as num')->select();

            $list[$k]['num'] = $num[0]['num'];

        }
        //var_dump($list);
        $this->assign('list',$list);
        $this->display();
    }

    // 增加 修改 角色
    public function role()
    {
        if(isset($_GET['rid'])){
            $role = M('role')->find($_GET['rid']);
            //var_dump($role);
            $roleList = M('role')->where('id !='.I('get.rid'))->field('id,name')->select();
            //var_dump($roleList);
            $this->assign('role',$role);
        }else{
            $roleList = M('role')->field('id,name')->select();
        }

        $this->assign('roleList',$roleList);

        $this->display();
    }

    //添加角色
    public function insertRole()
    {
        if(isset($_POST['name']) && isset($_POST['pid']) && isset($_POST['status'])) {
            $db = M('role');
            if ($db->create()){
                if($db->add()) $this->redirect('Role/index');
            }else{
                $this->error('数据不完整！');
            }
        }else{
           $this->error('数据不完整！');
        }

    }

    //保存修改
    public function saveRole()
    {
        if(isset($_POST['rid'])){
            if(isset($_POST['name']) && isset($_POST['pid']) && isset($_POST['status'])) {
                $db = M('role');
                if ($db->create()){
                    if($db->where('id='.I('post.rid'))->save()===false){
                        $this->error('角色修改失败！');
                    } else{
                        $this->redirect('Role/index');
                    }
                }else{
                    $this->error('数据不完整！');
                }
            }else{
                $this->error('数据不完整！');
            }
        }else{
            $this->error('非法操作，请按正常流程来操作！');
        }
    }

    //改变status
    //1 为开启 0 为禁止
    public function es()
    {
        if(isset($_GET['rid']) && isset($_GET['st'])){

            $status = $_GET['st'] == 1?0:1;
            $db = M('role')->where('id='.I('get.rid'))->setField('status',$status);
            if($db === false){
               $this->error('状态修改失败');
            }else{
                $this->redirect('Role/index');
            }

        }else{
            $this->error('非法操作，请按正常流程来操作！');
        }

    }
}